<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="data.queryParams" :inline="true">
            <el-form-item label="资源名称" prop="realName" label-width="96px">
              <el-input v-model="data.queryParams.realName" placeholder="请输入资源名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="分类" prop="parentId" label-width="96px">
                <el-select v-model="data.queryParams.parentId" placeholder="请选择分类" clearable>
                <el-option v-for="item in enterprise_material_catalogue" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" :icon="Plus" plain @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" :icon="Delete" plain @click="handleDelete" :disabled="selectionList.length === 0">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="roleTableRef" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="资源名称" prop="realName" :show-overflow-tooltip="true" />
        <el-table-column label="资源后缀" prop="suffix" :show-overflow-tooltip="true" />
        <el-table-column label="分类" prop="parentId" :show-overflow-tooltip="true" >
            <template #default="scope">
                <span>{{ enterprise_material_catalogue.find(item => item.value === scope.row.parentId)?.label }}</span>
            </template>
        </el-table-column>

        <el-table-column label="资源类型" prop="type" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" size="small" @click="editRow(scope.row)" />
            <el-button type="danger" :icon="Delete" size="small" @click="delRow([scope.row])" />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="data.queryParams.total > 0"
        v-model:page="data.queryParams.pageNum"
        v-model:limit="data.queryParams.pageSize"
        :total="data.queryParams.total"
        @pagination="getList"
      />
    </el-card>
    <el-dialog v-model="dialogVisible" :title="actionType === 'add' ? '新增' : '修改'" width="500" :before-close="handleClose">
      <el-form :model="addForm" ref="ruleFormRef" label-width="106px" :rules="rules">
        <el-form-item label="资源名称" prop="realName">
          <el-input v-model="addForm.realName" placeholder="请输入资源名称" />
        </el-form-item>
        <el-form-item label="分类" prop="parentId">
          <el-select v-model="addForm.parentId" placeholder="请选择分类" clearable>
                <el-option v-for="item in enterprise_material_catalogue" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
        </el-form-item>
        <el-form-item label="选择部门">
          <el-tag v-for="(item, index) in dialogDeptList" :key="index" style="margin-right: 5px">{{ item.deptName }}</el-tag>
          <el-button type="primary" @click="OpenYuSelectDeptClick">选择部门</el-button>
        </el-form-item>
        <el-form-item label="文件" class="UploadFileRef">
          <UploadFile
            :limit="1"
            ref="UploadFileRef"
            :multiple="false"
            describe="只能上传word/excel/ppt文件，且不超过10M"
            accept=".ppt,.pptx,.doc,.docx,.xls,.xlsx,.pdf"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择部门 -->
    <YuSelectDept ref="YuSelectDeptRefs" @handleNodeDblClick="handleNodeDblClick"></YuSelectDept>
  </div>
</template>

<script setup lang="ts">
import YuSelectDept from '@/views/templateManage/component/yu-select-dept.vue';
import UploadFile from '@/views/templateManage/component/uploadFile.vue';

import { getCalendarList, addCalendar, updateCalendar, deleteCalendar } from '@/api/resources/calendarManagementApi';
// api
import {
  get,
  apiEnterpriseMaterialFilesTreeGet,
  apiEnterpriseMaterialFilesTreePut,
  apiEnterpriseMaterialFilesTreeDelete,
  apiEnterpriseMaterialFilesTreePost
} from '@/api/resources/enterpriseResourceManageApi';
import { Delete, Plus, Edit } from '@element-plus/icons-vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { enterprise_material_catalogue } = toRefs<any>(proxy?.useDict('enterprise_material_catalogue'));
const loading = ref(true);
const showSearch = ref(true);
const dataList = ref([]);
const selectionList = ref([]);
const dialogVisible = ref(false);
const actionType = ref('add');
const ruleFormRef = ref<FormInstance>();
const addForm = reactive({
  realName: '',
  parentId: '',
  id:''
});
const rules = reactive<FormRules>({
  realName: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择分类', trigger: 'blur' }]
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
    realName: '',
    parentId:''

  }
});
/**
 * 查询模板列表
 */
const getList = async () => {
  loading.value = true;
  const res: any = await apiEnterpriseMaterialFilesTreeGet({
    page: data.queryParams.pageNum - 1,
    size: data.queryParams.pageSize,
    realName: data.queryParams.realName,
    parentId: data.queryParams.parentId
  });
  if (res.code == 200) {
    loading.value = false;
    dataList.value = res.rows;
    data.queryParams.total = res.total;
  }
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  data.queryParams.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  data.queryParams.realName = '';
  data.queryParams.parentId = '';
  handleQuery();
};
const handleSelectionChange = (val) => {
  selectionList.value = val;
};
const handleAdd = () => {
  dialogVisible.value = true;
  actionType.value = 'add';
};
const editRow = (row: any) => {
  dialogVisible.value = true;
  actionType.value = 'edit';
  dialogDeptList.value = [
    {
      deptId: row.deptId,
      deptName: row.deptName
    }
  ];
  Object.assign(addForm, row);
};
const UploadFileRef = ref(null);
// 新增or修改
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let formData = new FormData();
      formData.append('realName', addForm.realName);
      formData.append('parentId', addForm.parentId);
      let deptId = dialogDeptList.value.map((item: any) => item.deptId);
      formData.append('deptId', deptId.join(','));
      if (UploadFileRef.value.fileLis.length) {
        formData.append('file', UploadFileRef.value.fileLis[0].raw);
      }
      if (actionType.value == 'add') {
        const res = await apiEnterpriseMaterialFilesTreePost(formData);
        if (res.code == 200) {
          ElMessage.success('添加成功');
          getList();
          handleClose();
        }
      } else {
        formData.append('id', addForm.id);
        const res = await apiEnterpriseMaterialFilesTreePut(formData);
        if (res.code == 200) {
          ElMessage.success('修改成功');
          getList();
          handleClose();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
const delRow = (row:any) => {
  ElMessageBox.confirm('此操作将永久删除该模板, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let ids = row.map((item) => item.id);
    const res = await apiEnterpriseMaterialFilesTreeDelete(ids);
    if (res.code == 200) {
      ElMessage.success('删除成功');
      getList();
    }
  });
};
const handleClose = () => {
  dialogVisible.value = false;
  dialogDeptList.value = [];
  UploadFileRef.value.fileLis = []
  ruleFormRef.value?.resetFields();
};
/**删除按钮操作 */
const handleDelete = async () => {
  ElMessageBox.confirm('此操作将永久删除该模板, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const ids = selectionList.value.map((item) => item.id);
      const res = await apiEnterpriseMaterialFilesTreeDelete(ids);
      if (res.code == 200) {
        ElMessage.success('删除成功');
        getList();
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

// 打开选择部门对话框
const YuSelectDeptRefs = ref(null);
const OpenYuSelectDeptClick = () => {
  YuSelectDeptRefs.value.dialogTransfer = true;
};
// 选择部门确定事件
const dialogDeptList = ref([]);
const handleNodeDblClick = (val: any) => {
  dialogDeptList.value = [JSON.parse(JSON.stringify(val))];
};
onMounted(() => {
  getList();
});
</script>